package com.qudian.pay.notify.dingtalk;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
import com.qudian.pay.notify.dingtalk.message.Message;

/**
 * @Description: 钉钉机器人客户端
 * @author gaoxiang
 * @date 2017年6月8日 下午6:17:48
 */ 
public class DingtalkChatbotClient {
	
	HttpClient httpclient = HttpClients.createDefault();
	
	public SendResult send(String webhook, Message message) {
		HttpPost httppost = new HttpPost(webhook);
		httppost.addHeader("Content-Type", "application/json; charset=utf-8");
		StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
		httppost.setEntity(se);
		SendResult sendResult = new SendResult();
		try {
			HttpResponse response = httpclient.execute(httppost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(response.getEntity());
				JSONObject obj = JSONObject.parseObject(result);
				Integer errcode = obj.getInteger("errcode");
				sendResult.setErrorCode(errcode);
				sendResult.setErrorMsg(obj.getString("errmsg"));
				sendResult.setIsSuccess(errcode.equals(0));
			}
		} catch (Exception e) {
			sendResult.setErrorCode(-1);
			sendResult.setErrorMsg("系统异常了,"+e.getCause());
			sendResult.setIsSuccess(false);
		}
		return sendResult;
	}
}
